﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the GNU General Public License version 2 (GPLv2).
// See accompanying file License.txt or copy at http://phuse.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Phuse.Net
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>Simplifies the creation of a <see cref="ClientBaseException"/> subclass object.</summary>
    internal struct ExceptionHelper
    {
        private static readonly Type[] StringParameter = new Type[] { typeof(string) };
        private static readonly Type[] StringAndExceptionParameters = new Type[] { typeof(string), typeof(Exception) };

        private readonly IEnumerable<string> responseLineWords;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        internal ExceptionHelper(IEnumerable<string> responseLineWords)
        {
            this.responseLineWords = responseLineWords;
        }

        internal Exception CreateException<TException>() where TException : Exception
        {
            return (Exception)typeof(TException).GetConstructor(StringParameter).Invoke(
                new object[] { this.JoinResponseLineWords() });
        }

        internal Exception CreateException<TException>(Exception innerException) where TException : Exception
        {
            return (Exception)typeof(TException).GetConstructor(StringAndExceptionParameters).Invoke(
                new object[] { this.JoinResponseLineWords(), innerException });
        }

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private string JoinResponseLineWords()
        {
            return string.Join(" ", this.responseLineWords.ToArray());
        }
    }
}
